package com.zkflzl.mianshi.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

public class MyFileUtils {
    private static final Logger log = LoggerFactory.getLogger(MyFileUtils.class);

    /**
     * 检查MultipartFile是否为图片
     */
    public static boolean isNotValidImage(MultipartFile file) {
        if (file.isEmpty()) {
            log.warn("文件为空");
            return true;
        }
        // 特判
        String fileName = file.getOriginalFilename();
        // 获取文件后缀
        String suffix = Objects.requireNonNull(fileName).substring(fileName.lastIndexOf(".") + 1);
        if (suffix.equals("webp") || suffix.equals("svg")) {
            return false;
        }
        // 使用try-with-resources语句自动关闭InputStream
        try (InputStream inputStream = file.getInputStream()) {
            BufferedImage image = ImageIO.read(inputStream);
            if (image == null || image.getWidth() <= 0 || image.getHeight() <= 0) {
                log.warn("文件不是有效的图片或图片尺寸不正确");
                return true;
            }
            return false;
        } catch (IOException e) {
            log.error("读取文件或判断图片时发生异常", e);
            return true;
        }
    }


    /**
     * 判断是否为xlsx文件
     *
     * @param file 文件
     * @return 是否为xlsx文件
     */
    public static boolean isXlsxFile(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        if (!"xlsx".equals(originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length()))) {
            return false;
        }
        String contentType = file.getContentType();
        return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(contentType);
    }
}
